<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>港口</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="港口名称">
              <a-input v-model="searchForm.portNameLike"/>
            </a-form-item>
            <a-form-item label="所属省市">
              <a-cascader
                :options="options"
                :fieldNames="{label: 'area', value: 'area', children: 'childList'}"
                placeholder="请选择"
                @change="onChange1"
              />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model="searchForm.status" class="selectWidth">
                <a-select-option key="">全部</a-select-option>
                <a-select-option :key="1">正常</a-select-option>
                <a-select-option :key="0">冻结</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="openCreate">+  创建港口</a-button>
            </a-form-item>
          </a-form>

          <a-table :columns="columns" :data-source="tableData" :loading="tloading" class="tableMargin" :pagination="pagination" rowKey="id">
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="operation" slot-scope="text, record">
              <a @click="freezeIt(record.id, record.status)">{{record.status === 1 ? '冻结': (record.status === 0 ? '恢复':'')}}</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <a-modal :visible="visible" title="创建港口" @ok="handleOk" @cancel="handleCancel" centered :destroyOnClose='true' :confirmLoading="confirmLoading">
      <a-form-model ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="港口名称" prop="name">
          <a-input v-model="form.name" :max-length="20"/>
        </a-form-model-item>
        <a-form-model-item label="所属省市" prop="province">
          <a-cascader
            :options="options"
            :fieldNames="{label: 'area', value: 'area', children: 'childList'}"
            placeholder="请选择"
            @change="onChange2"
          />
        </a-form-model-item>
        <a-form-model-item label="状态">
          <a-select v-model="form.status">
            <a-select-option :key="1">正常</a-select-option>
            <a-select-option :key="0">冻结</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="是否有箱管">
          <a-select v-model="form.isContainerManagement">
            <a-select-option :key="1">是</a-select-option>
            <a-select-option :key="0">否</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item v-if="form.isContainerManagement===1" label="港口应付结算对象" prop="custId">
          <a-select
            show-search
            :show-arrow="false"
            :filter-option="false" :default-active-first-option="false"
            :not-found-content="null"
            v-model="form.custId"
            @search="handleNameChange"
          >
            <a-select-option v-for="d in nameLikeData" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item v-if="form.isContainerManagement===1" label="空箱装卸费（20GP）" prop="smallEmptyHandlingCost">
          <a-input-number v-model="form.smallEmptyHandlingCost" style="width: 100%"/>
        </a-form-model-item>
        <a-form-model-item v-if="form.isContainerManagement===1" label="重箱装卸费（20GP）" prop="smallLoadedHandlingCost">
         <a-input-number v-model="form.smallLoadedHandlingCost" style="width: 100%"/>
        </a-form-model-item>
        <a-form-model-item v-if="form.isContainerManagement===1" label="空箱装卸费（40HC）" prop="emptyHandlingCost">
          <a-input-number v-model="form.emptyHandlingCost" style="width: 100%"/>
        </a-form-model-item>
        <a-form-model-item v-if="form.isContainerManagement===1" label="重箱装卸费（40HC）" prop="loadedHandlingCost">
         <a-input-number v-model="form.loadedHandlingCost" style="width: 100%"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { queryBaseAreaList, queryCustNameList } from '@/api'
import {queryPortList, editPort, addPort} from '@/api/systemPersonnelManage'

const fomrMessage = `必填项不能为空`
const defaultForm = () => ({
  name: '', // 港口
  isContainerManagement: 1, // 是否有箱管：1是，0否
  custId: null, // 结算对象
  emptyHandlingCost: '', // 空箱装卸费
  loadedHandlingCost: '', // 重箱装卸费
  smallEmptyHandlingCost: '',
  smallLoadedHandlingCost: '',
  status: 1, // 状态：1正常，0冻结
  province: '', // 省
  city: '' // 市
})

export default {
  data () {
    this.handleNameChange = debounce(this.handleNameChange, 800)
    return {
      searchForm: {
        portNameLike: '',
        status: '',
        city: '',
        province: ''
      },
      tloading: false,
      columns: [{
        title: '序号',
        width: 60,
        scopedSlots: {customRender: 'rn'}
      }, {
        title: '港口名称',
        dataIndex: 'name',
        ellipsis: true
      }, {
        title: '所属省市',
        customRender: (text, record) => {
          return `${record.province} ${record.city}`
        }
      }, {
        title: '是否有箱管',
        dataIndex: 'isContainerManagement',
        customRender: (text, record) => {
          return text === 1 ? '是' : '否'
        }
      }, {
        title: '空箱装卸费（20GP/元）',
        dataIndex: 'smallEmptyHandlingCost',
        customRender: (text, record) => {
          return text || '--'
        }
      }, {
        title: '重箱装卸费（20GP/元）',
        dataIndex: 'smallLoadedHandlingCost',
        customRender: (text, record) => {
          return text || '--'
        }
      }, {
        title: '空箱装卸费（40HC/元）',
        dataIndex: 'emptyHandlingCost',
        customRender: (text, record) => {
          return text || '--'
        }
      }, {
        title: '重箱装卸费（40HC/元）',
        dataIndex: 'loadedHandlingCost',
        customRender: (text, record) => {
          return text || '--'
        }
      }, {
        title: '港口应付结算对象',
        dataIndex: 'custName',
        customRender: (text, record) => {
          return text || '--'
        }
      }, {
        title: '状态',
        dataIndex: 'status',
        customRender: (text, row, index) => {
          if (text === 1) {
            return <a-badge status="success" text="正常"/>
          } else if (text === 0) {
            return <a-badge status="error" text="冻结"/>
          }
        }
      }, {
        title: '操作',
        width: 100,
        scopedSlots: {customRender: 'operation'}
      }],
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      visible: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      form: defaultForm(),
      rules: {
        name: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        emptyHandlingCost: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        loadedHandlingCost: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        smallEmptyHandlingCost: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        smallLoadedHandlingCost: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        province: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        custId: [
          { required: true, message: fomrMessage, trigger: ['blur', 'change'] }
        ]
      },
      options: [], // 省市
      nameLikeData: '',
      confirmLoading: false
    }
  },
  methods: {
    handleNameChange (nameLike) {
      if (nameLike) {
        queryCustNameList({
          nameLike,
          belongCompany: 'JIA_HUA',
          custTypeLike: 'SUPPLIER',
          status: 1,
          isPayable: 1
        }).then(rsp => {
          this.nameLikeData = rsp.data
        })
      } else {
        this.nameLikeData = []
      }
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.tloading = true
      queryPortList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.tloading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })
    },
    freezeIt (id, isFrozen) {
      if (!this.$root._bc.frozen) {
        this.$message.error('您无此权限！')
        return
      }
      let text = '确定冻结吗？'
      let successText = '冻结成功！'
      if (isFrozen === 0) {
        text = '确定恢复正常吗？'
        successText = '恢复成功！'
      }

      let _this = this
      this.$confirm({
        title: text,
        okType: 'danger',
        onOk () {
          editPort({id, status: 1 - isFrozen}).then(rsp => {
            _this.$message.success(successText)
            _this.handleSubmit()
          })
        }
      })
    },
    onChange1 (value, selectedOptions) {
      this.searchForm.province = value[0]
      this.searchForm.city = value[1]
    },
    onChange2 (value, selectedOptions) {
      this.form.province = value[0]
      this.form.city = value[1]
    },
    openCreate () {
      if (!this.$root._bc.create) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.$refs.form) this.$refs.form.resetFields()
      this.visible = true
      this.form = defaultForm()
    },
    handleOk () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          addPort(this.form).then(rsp => {
            this.$message.success('创建成功')
            this.handleSubmit()
            this.visible = false
            setTimeout(() => { this.confirmLoading = false }, 1000)
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.$refs.form.resetFields()
    }
  },
  created () {
    this.handleSubmit()
    queryBaseAreaList({}).then(res => {
      this.options = res.data.map(item => {
        item.childList.map(c => {
          delete c.childList
        })

        return item
      })
    }).catch(rs => {})
  },
  watch: {
    'form.isContainerManagement' () {
      this.form.custId = ''
      this.form.emptyHandlingCost = ''
      this.form.loadedHandlingCost = ''
      this.form.smallEmptyHandlingCost = ''
      this.form.smallLoadedHandlingCost = ''
    }
  }
}
</script>

<style lang="less" scoped>
</style>
